package com.yfbao.encryptor;

import com.yfbao.config.FieldEncrypt;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Properties;

@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
@Component
public class EncryptionInterceptor implements Interceptor {

    @Autowired
    private AESEncryptor encryptor;

    @Autowired
    private QueryConditionEncryptor conditionEncryptor;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object parameter = invocation.getArgs()[1];
        String methodName = invocation.getMethod().getName();

//        // 处理查询条件的加密
//        if ("query".equals(methodName) && parameter != null) {
//            encryptQueryConditions(parameter);
//        }

        // 处理插入和更新操作的参数加密
        if ("update".equals(methodName) && parameter != null) {
            encryptParameters(parameter);
        }

        Object result = invocation.proceed();

        // 处理查询结果解密
        if (result != null && invocation.getMethod().getName().equals("query")) {
            decryptResult(result);
        }

        return result;
    }


    /**
     * 加密查询条件
     */
    private void encryptQueryConditions(Object parameter) {
        if (parameter instanceof Map) {
            encryptMapConditions((Map<String, Object>) parameter);
        } else {
            // 处理实体类作为查询条件的情况
            processEntityConditions(parameter);
        }
    }

    /**
     * 加密Map中的查询条件
     */
    private void encryptMapConditions(Map<String, Object> paramMap) {
        if (paramMap == null || paramMap.isEmpty()) {
            return;
        }

        // 获取实体类类型
        Class<?> entityClass = getEntityClassFromMap(paramMap);
        if (entityClass == null) {
            return;
        }

        // 处理各种查询条件
        for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();

            if (value == null) {
                continue;
            }

            // 处理Wrapper条件
            if (key.startsWith("ew")) {
                encryptWrapperConditions(value, entityClass);
            }
            // 处理直接字段条件
            else if (isFieldCondition(key) && value instanceof String) {
                String fieldName = conditionEncryptor.columnToFieldName(key);
                if (conditionEncryptor.needEncryptQuery(fieldName, entityClass)) {
                    paramMap.put(key, conditionEncryptor.encryptCondition(value));
                }
            }
        }
    }

    /**
     * 处理Wrapper查询条件加密
     */
    private void encryptWrapperConditions(Object wrapper, Class<?> entityClass) {
        if (wrapper == null) return;

        try {
            // 处理不同类型的Wrapper
            Class<?> wrapperClass = wrapper.getClass();

            // 处理LambdaQueryWrapper等常见Wrapper类型
            if (wrapperClass.getName().contains("Wrapper")) {
                // 尝试获取表达式或条件列表
                try {
                    Field expressionListField = wrapperClass.getDeclaredField("expressionList");
                    expressionListField.setAccessible(true);
                    Object expressionList = expressionListField.get(wrapper);

                    if (expressionList instanceof List) {
                        encryptExpressionList((List<?>) expressionList, entityClass);
                    }
                } catch (NoSuchFieldException e) {
                    // 尝试其他可能的字段名
                    try {
                        Field expressionsField = wrapperClass.getDeclaredField("expressions");
                        expressionsField.setAccessible(true);
                        Object expressions = expressionsField.get(wrapper);

                        if (expressions instanceof List) {
                            encryptExpressionList((List<?>) expressions, entityClass);
                        }
                    } catch (NoSuchFieldException ex) {
                        // 忽略，继续尝试其他方式
                    }
                }
            }
        } catch (Exception e) {
            System.err.println("加密Wrapper条件失败: " + e.getMessage());
        }
    }

    /**
     * 加密表达式列表
     */
    private void encryptExpressionList(List<?> expressions, Class<?> entityClass) {
        if (expressions == null || expressions.isEmpty()) {
            return;
        }

        for (Object expression : expressions) {
            if (expression == null) continue;

            try {
                // 处理不同类型的表达式
                Class<?> expressionClass = expression.getClass();

                // 尝试获取列名和值字段
                Field[] fields = expressionClass.getDeclaredFields();
                String columnName = null;
                Object valueObj = null;

                for (Field field : fields) {
                    if (field.getName().equals("column")) {
                        field.setAccessible(true);
                        Object columnObj = field.get(expression);
                        if (columnObj instanceof String) {
                            columnName = (String) columnObj;
                        }
                    } else if (field.getName().equals("value")) {
                        field.setAccessible(true);
                        valueObj = field.get(expression);
                    }
                }

                if (columnName != null && valueObj != null) {
                    String fieldName = conditionEncryptor.columnToFieldName(columnName);

                    if (conditionEncryptor.needEncryptQuery(fieldName, entityClass) && valueObj instanceof String) {
                        Object encryptedValue = conditionEncryptor.encryptCondition(valueObj);

                        // 查找value字段并设置加密后的值
                        for (Field field : fields) {
                            if (field.getName().equals("value")) {
                                field.setAccessible(true);
                                field.set(expression, encryptedValue);
                                break;
                            }
                        }

                        System.out.println("加密查询条件: " + columnName + " = " + valueObj + " -> " + encryptedValue);
                    }
                }
            } catch (Exception e) {
                // 忽略无法处理的表达式类型
            }
        }
    }

    /**
     * 处理实体类作为查询条件的情况
     */
    private void processEntityConditions(Object entity) {
        if (!isEntity(entity)) {
            return;
        }

        Class<?> clazz = entity.getClass();
        while (clazz != null && clazz != Object.class) {
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                if (field.isAnnotationPresent(FieldEncrypt.class)) {
                    try {
                        field.setAccessible(true);
                        Object value = field.get(entity);
                        if (value instanceof String) {
                            String encrypted = encryptor.encrypt((String) value);
                            field.set(entity, encrypted);
                        }
                    } catch (Exception e) {
                        System.err.println("加密查询条件字段失败: " + field.getName());
                    }
                }
            }
            clazz = clazz.getSuperclass();
        }
    }

    /**
     * 从Map参数中推断实体类类型
     */
    private Class<?> getEntityClassFromMap(Map<String, Object> paramMap) {
        // 尝试从et参数获取实体类
        if(paramMap.keySet().contains("et")){
            Object et = paramMap.get("et");
            if (et != null && isEntity(et)) {
                return et.getClass();
            }
        }


        // 尝试从ew参数获取实体类
        if(paramMap.containsKey("ew")){
            Object ew = paramMap.get("ew");
            if (ew != null) {
                try {
                    Field entityClassField = ew.getClass().getDeclaredField("entityClass");
                    entityClassField.setAccessible(true);
                    Object entityClass = entityClassField.get(ew);
                    if (entityClass instanceof Class) {
                        return (Class<?>) entityClass;
                    }
                } catch (Exception e) {
                    // 忽略异常
                }
            }
        }

        return null;
    }

    private boolean isFieldCondition(String key) {
        return !key.startsWith("ew") &&
                !key.startsWith("et") &&
                !key.startsWith("param") &&
                !"id".equals(key);
    }

    private void encryptParameters(Object parameter) {
        if (parameter == null) return;

        if (parameter instanceof Map) {
            // 处理Map参数
            ((Map<?, ?>) parameter).values().forEach(this::processEntity);
        } else if (isEntity(parameter)) {
            // 处理实体类参数
            processEntity(parameter);
        }
    }

    private void processEntity(Object entity) {
        if (entity == null) return;

        Class<?> clazz = entity.getClass();
        // 获取所有字段
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            if (field.isAnnotationPresent(FieldEncrypt.class)) {
                encryptField(entity, field);
            }
        }
    }

    private void encryptField(Object entity, Field field) {
        try {
            field.setAccessible(true);
            Object value = field.get(entity);
            if (value instanceof String) {
                String encrypted = encryptor.encrypt((String) value);
                field.set(entity, encrypted);
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException("字段加密失败", e);
        }
    }

    private void decryptResult(Object result) {
        if (result == null) return;

        if (result instanceof List) {
            ((List<?>) result).forEach(this::decryptEntity);
        } else if (result.getClass().isArray()) {
            Object[] array = (Object[]) result;
            for (Object item : array) {
                decryptEntity(item);
            }
        } else {
            decryptEntity(result);
        }
    }


    private void decryptEntity(Object entity) {
        if (entity == null || !isEntity(entity)) return;

        Class<?> clazz = entity.getClass();
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            if (field.isAnnotationPresent(FieldEncrypt.class)) {
                decryptField(entity, field);
            }
        }
    }

    private void decryptField(Object entity, Field field) {
        try {
            field.setAccessible(true);
            Object value = field.get(entity);
            if (value instanceof String) {
                String decrypted = encryptor.decrypt((String) value);
                field.set(entity, decrypted);
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException("字段解密失败", e);
        }
    }

    private boolean isEntity(Object obj) {
        return !(obj instanceof Map || obj instanceof Collection || obj.getClass().isPrimitive()
                || obj.getClass().isArray() || obj instanceof String || obj instanceof Number);
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // 可配置属性
    }
}
